package com.geek.water.controller;

import com.geek.water.result.Result;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 通知管理控制器
 */
@RestController
@RequestMapping("/api/notification")
public class NotificationController {

    /**
     * 获取通知统计信息
     */
    @GetMapping("/stats")
    public Result getNotificationStats() {
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalOverdue", 10);
        stats.put("totalAmount", 15000.00);
        stats.put("sentCount", 8);
        stats.put("paidCount", 2);
        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "获取成功", stats);
    }

    /**
     * 获取通知任务列表
     */
    @GetMapping("/tasks")
    public Result getTaskList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        result.put("list", new Object[0]);
        result.put("total", 0);
        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "获取成功", result);
    }

    /**
     * 创建通知任务
     */
    @PostMapping("/tasks")
    public Result createNotificationTask(@RequestBody Map<String, Object> task) {
        String taskId = "TASK_" + System.currentTimeMillis();
        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "任务创建成功", taskId);
    }

    /**
     * 获取发送日志
     */
    @GetMapping("/send-logs")
    public Result getSendLogs(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        result.put("list", new Object[0]);
        result.put("total", 0);
        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "获取成功", result);
    }

    /**
     * 获取通知配置
     */
    @GetMapping("/config")
    public Result getNotificationConfig() {
        Map<String, Object> config = new HashMap<>();
        config.put("systemName", "智慧水务管理平台");
        config.put("adminEmail", "admin@example.com");
        config.put("smtpHost", "smtp.example.com");
        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "获取成功", config);
    }

    /**
     * 更新通知配置
     */
    @PutMapping("/config")
    public Result updateNotificationConfig(@RequestBody Map<String, Object> config) {
        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "配置更新成功");
    }

    /**
     * 测试通知发送
     */
    @PostMapping("/test")
    public Result testNotification(@RequestBody Map<String, Object> request) {
        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "测试通知发送成功");
    }

    // ==================== 催缴提醒相关接口 ====================

    /**
     * 获取催缴策略列表
     */
    @GetMapping("/collection/strategies")
    public Result getCollectionStrategies() {
        List<Map<String, Object>> strategies = new ArrayList<>();

        Map<String, Object> strategy1 = new HashMap<>();
        strategy1.put("id", 1);
        strategy1.put("strategyName", "逾期7天提醒");
        strategy1.put("daysOverdue", 7);
        strategy1.put("notificationChannels", "[\"email\",\"sms\"]");
        strategy1.put("priority", "高");
        strategy1.put("isActive", true);

        Map<String, Object> strategy2 = new HashMap<>();
        strategy2.put("id", 2);
        strategy2.put("strategyName", "逾期15天提醒");
        strategy2.put("daysOverdue", 15);
        strategy2.put("notificationChannels", "[\"email\",\"sms\",\"app_push\"]");
        strategy2.put("priority", "中");
        strategy2.put("isActive", true);

        strategies.add(strategy1);
        strategies.add(strategy2);

        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "获取成功", strategies);
    }

    /**
     * 创建催缴策略
     */
    @PostMapping("/collection/strategies")
    public Result createCollectionStrategy(@RequestBody Map<String, Object> strategy) {
        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "策略创建成功");
    }

    /**
     * 更新催缴策略
     */
    @PutMapping("/collection/strategies/{id}")
    public Result updateCollectionStrategy(@PathVariable Long id, @RequestBody Map<String, Object> strategy) {
        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "策略更新成功");
    }

    /**
     * 删除催缴策略
     */
    @DeleteMapping("/collection/strategies/{id}")
    public Result deleteCollectionStrategy(@PathVariable Long id) {
        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "策略删除成功");
    }

    /**
     * 获取催缴任务列表
     */
    @GetMapping("/collection/tasks")
    public Result getCollectionTasks(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer size) {
        Map<String, Object> result = new HashMap<>();

        List<Map<String, Object>> tasks = new ArrayList<>();
        Map<String, Object> task = new HashMap<>();
        task.put("id", 1);
        task.put("bill_code", "BILL202401001");
        task.put("customer_name", "测试客户1");
        task.put("overdue_days", 15);
        task.put("amount", 1500.00);
        task.put("strategy_name", "逾期15天提醒");
        task.put("status", "pending");
        task.put("scheduled_at", "2024-01-15 10:00:00");
        task.put("sent_at", null);
        tasks.add(task);

        result.put("list", tasks);
        result.put("total", 1);

        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "获取成功", result);
    }

    /**
     * 生成催缴任务
     */
    @PostMapping("/collection/tasks/generate")
    public Result generateCollectionTasks() {
        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "催缴任务生成成功");
    }

    /**
     * 发送催缴任务
     */
    @PostMapping("/collection/tasks/{id}/send")
    public Result sendCollectionTask(@PathVariable Long id) {
        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "催缴通知发送成功");
    }

    /**
     * 确认催缴任务
     */
    @PostMapping("/collection/tasks/{id}/confirm")
    public Result confirmCollectionTask(@PathVariable Long id) {
        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "任务状态更新成功");
    }

    /**
     * 获取催缴记录列表
     */
    @GetMapping("/collection/records")
    public Result getCollectionRecords(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(required = false) String customerName,
            @RequestParam(required = false) String billCode,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        Map<String, Object> result = new HashMap<>();

        List<Map<String, Object>> records = new ArrayList<>();
        Map<String, Object> record1 = new HashMap<>();
        record1.put("id", 1);
        record1.put("bill_code", "BILL202401001");
        record1.put("customer_name", "测试客户1");
        record1.put("overdue_days", 15);
        record1.put("amount", 1500.00);
        record1.put("strategy_name", "逾期15天提醒");
        record1.put("notification_channel", "[\"email\",\"sms\"]");
        record1.put("status", "sent");
        record1.put("sent_at", "2024-01-15 10:30:00");
        record1.put("response_at", "2024-01-15 11:00:00");
        record1.put("payment_at", null);

        Map<String, Object> record2 = new HashMap<>();
        record2.put("id", 2);
        record2.put("bill_code", "BILL202401002");
        record2.put("customer_name", "测试客户2");
        record2.put("overdue_days", 7);
        record2.put("amount", 800.00);
        record2.put("strategy_name", "逾期7天提醒");
        record2.put("notification_channel", "[\"email\"]");
        record2.put("status", "paid");
        record2.put("sent_at", "2024-01-10 09:00:00");
        record2.put("response_at", "2024-01-10 09:30:00");
        record2.put("payment_at", "2024-01-10 15:00:00");

        Map<String, Object> record3 = new HashMap<>();
        record3.put("id", 3);
        record3.put("bill_code", "BILL202401003");
        record3.put("customer_name", "测试客户3");
        record3.put("overdue_days", 20);
        record3.put("amount", 2000.00);
        record3.put("strategy_name", "逾期15天提醒");
        record3.put("notification_channel", "[\"sms\",\"app_push\"]");
        record3.put("status", "failed");
        record3.put("sent_at", null);
        record3.put("response_at", null);
        record3.put("payment_at", null);

        records.add(record1);
        records.add(record2);
        records.add(record3);

        result.put("list", records);
        result.put("total", 3);

        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "获取成功", result);
    }

    /**
     * 重新发送催缴通知
     */
    @PostMapping("/collection/records/{id}/resend")
    public Result resendCollectionNotification(@PathVariable Long id) {
        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "重新发送成功");
    }

    /**
     * 导出催缴记录
     */
    @GetMapping("/collection/records/export")
    public Result exportCollectionRecords(
            @RequestParam(required = false) String customerName,
            @RequestParam(required = false) String billCode,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "导出成功", "催缴记录.xlsx");
    }

    // ==================== 故障与工单预警相关接口 ====================

    /**
     * 获取预警配置列表
     */
    @GetMapping("/alert/configs")
    public Result getAlertConfigs() {
        List<Map<String, Object>> configs = new ArrayList<>();

        Map<String, Object> config1 = new HashMap<>();
        config1.put("id", 1);
        config1.put("ruleName", "水压异常预警");
        config1.put("deviceType", "sensor");
        config1.put("threshold", "> 0.8MPa");
        config1.put("alertLevel", "high");
        config1.put("notificationChannels", "[\"email\",\"sms\"]");
        config1.put("isActive", true);

        Map<String, Object> config2 = new HashMap<>();
        config2.put("id", 2);
        config2.put("ruleName", "流量异常预警");
        config2.put("deviceType", "water_meter");
        config2.put("threshold", "< 0.1L/min");
        config2.put("alertLevel", "medium");
        config2.put("notificationChannels", "[\"email\",\"app_push\"]");
        config2.put("isActive", true);

        configs.add(config1);
        configs.add(config2);

        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "获取成功", configs);
    }

    /**
     * 创建预警配置
     */
    @PostMapping("/alert/configs")
    public Result createAlertConfig(@RequestBody Map<String, Object> config) {
        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "预警配置创建成功");
    }

    /**
     * 更新预警配置
     */
    @PutMapping("/alert/configs/{id}")
    public Result updateAlertConfig(@PathVariable Long id, @RequestBody Map<String, Object> config) {
        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "预警配置更新成功");
    }

    /**
     * 删除预警配置
     */
    @DeleteMapping("/alert/configs/{id}")
    public Result deleteAlertConfig(@PathVariable Long id) {
        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "预警配置删除成功");
    }

    /**
     * 获取预警记录列表
     */
    @GetMapping("/alert/records")
    public Result getAlertRecords(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer size) {
        Map<String, Object> result = new HashMap<>();

        List<Map<String, Object>> records = new ArrayList<>();
        Map<String, Object> record1 = new HashMap<>();
        record1.put("id", 1);
        record1.put("deviceName", "水压传感器-001");
        record1.put("deviceType", "sensor");
        record1.put("alertType", "pressure_high");
        record1.put("alertLevel", "high");
        record1.put("description", "水压超过正常范围，当前值：0.85MPa");
        record1.put("status", "pending");
        record1.put("createdAt", "2024-01-15 10:30:00");
        record1.put("resolvedAt", null);

        Map<String, Object> record2 = new HashMap<>();
        record2.put("id", 2);
        record2.put("deviceName", "智能水表-002");
        record2.put("deviceType", "water_meter");
        record2.put("alertType", "flow_low");
        record2.put("alertLevel", "medium");
        record2.put("description", "流量异常偏低，当前值：0.05L/min");
        record2.put("status", "processing");
        record2.put("createdAt", "2024-01-15 09:15:00");
        record2.put("resolvedAt", null);

        records.add(record1);
        records.add(record2);

        result.put("list", records);
        result.put("total", 2);

        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "获取成功", result);
    }

    // ==================== 消息模板管理相关接口 ====================

    /**
     * 获取消息模板列表
     */
    @GetMapping("/templates")
    public Result getMessageTemplates(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String language) {
        Map<String, Object> result = new HashMap<>();

        List<Map<String, Object>> templates = new ArrayList<>();

        Map<String, Object> template1 = new HashMap<>();
        template1.put("id", 1);
        template1.put("name", "催缴通知模板");
        template1.put("code", "COLLECTION_001");
        template1.put("type", "collection");
        template1.put("subject", "账单催缴通知");
        template1.put("content", "尊敬的{{customerName}}，您的账单{{billCode}}已逾期{{overdueDays}}，逾期金额{{amount}}，请及时缴费。");
        template1.put("language", "zh-CN");
        template1.put("channels", "[\"email\",\"sms\"]");
        template1.put("isActive", true);
        template1.put("remark", "用于催缴逾期账单的通知模板");

        Map<String, Object> template2 = new HashMap<>();
        template2.put("id", 2);
        template2.put("name", "设备故障预警模板");
        template2.put("code", "ALERT_001");
        template2.put("type", "alert");
        template2.put("subject", "设备故障预警");
        template2.put("content", "检测到设备{{deviceName}}发生{{description}}，预警级别：{{alertLevel}}，请及时处理。");
        template2.put("language", "zh-CN");
        template2.put("channels", "[\"email\",\"app_push\"]");
        template2.put("isActive", true);
        template2.put("remark", "用于设备故障预警的通知模板");

        Map<String, Object> template3 = new HashMap<>();
        template3.put("id", 3);
        template3.put("name", "支付成功通知模板");
        template3.put("code", "PAYMENT_001");
        template3.put("type", "payment");
        template3.put("subject", "支付成功通知");
        template3.put("content", "尊敬的{{customerName}}，您的{{amount}}支付已成功，支付方式：{{paymentMethod}}，支付时间：{{paymentTime}}。");
        template3.put("language", "zh-CN");
        template3.put("channels", "[\"email\",\"sms\"]");
        template3.put("isActive", true);
        template3.put("remark", "用于支付成功的通知模板");

        Map<String, Object> template4 = new HashMap<>();
        template4.put("id", 4);
        template4.put("name", "系统维护通知模板");
        template4.put("code", "SYSTEM_001");
        template4.put("type", "system");
        template4.put("subject", "系统维护通知");
        template4.put("content", "{{systemName}}将于{{timestamp}}进行系统维护，{{message}}，请提前做好准备。");
        template4.put("language", "zh-CN");
        template4.put("channels", "[\"email\",\"app_push\"]");
        template4.put("isActive", true);
        template4.put("remark", "用于系统维护的通知模板");

        templates.add(template1);
        templates.add(template2);
        templates.add(template3);
        templates.add(template4);

        // 简单的搜索过滤
        if (name != null && !name.isEmpty()) {
            templates = templates.stream()
                    .filter(t -> t.get("name").toString().contains(name))
                    .collect(Collectors.toList());
        }

        if (type != null && !type.isEmpty()) {
            templates = templates.stream()
                    .filter(t -> type.equals(t.get("type")))
                    .collect(Collectors.toList());
        }

        if (language != null && !language.isEmpty()) {
            templates = templates.stream()
                    .filter(t -> language.equals(t.get("language")))
                    .collect(Collectors.toList());
        }

        result.put("list", templates);
        result.put("total", templates.size());

        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "获取成功", result);
    }

    /**
     * 创建消息模板
     */
    @PostMapping("/templates")
    public Result createMessageTemplate(@RequestBody Map<String, Object> template) {
        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "模板创建成功");
    }

    /**
     * 更新消息模板
     */
    @PutMapping("/templates/{id}")
    public Result updateMessageTemplate(@PathVariable Long id, @RequestBody Map<String, Object> template) {
        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "模板更新成功");
    }

    /**
     * 删除消息模板
     */
    @DeleteMapping("/templates/{id}")
    public Result deleteMessageTemplate(@PathVariable Long id) {
        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "模板删除成功");
    }

    /**
     * 切换模板状态
     */
    @PutMapping("/templates/{id}/status")
    public Result toggleTemplateStatus(@PathVariable Long id, @RequestBody Map<String, Object> request) {
        Boolean isActive = (Boolean) request.get("isActive");
        return new Result(com.geek.water.constant.CodeConstant.SUCCESS,
                isActive ? "模板启用成功" : "模板禁用成功");
    }

    /**
     * 测试发送模板消息
     */
    @PostMapping("/templates/{id}/test")
    public Result testTemplateMessage(@PathVariable Long id, @RequestBody Map<String, Object> request) {
        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "测试消息发送成功");
    }

    /**
     * 获取模板变量列表
     */
    @GetMapping("/templates/variables")
    public Result getTemplateVariables(@RequestParam String type) {
        Map<String, Object> variables = new HashMap<>();

        if ("collection".equals(type)) {
            variables.put("customerName", "客户姓名");
            variables.put("billCode", "账单编号");
            variables.put("amount", "逾期金额");
            variables.put("overdueDays", "逾期天数");
            variables.put("dueDate", "到期日期");
        } else if ("alert".equals(type)) {
            variables.put("deviceName", "设备名称");
            variables.put("deviceType", "设备类型");
            variables.put("alertLevel", "预警级别");
            variables.put("alertTime", "预警时间");
            variables.put("description", "故障描述");
        } else if ("payment".equals(type)) {
            variables.put("customerName", "客户姓名");
            variables.put("amount", "支付金额");
            variables.put("paymentTime", "支付时间");
            variables.put("paymentMethod", "支付方式");
        } else {
            variables.put("systemName", "系统名称");
            variables.put("message", "系统消息");
            variables.put("timestamp", "时间戳");
        }

        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "获取成功", variables);
    }
}
